package cn.gson.crmdemo.controller.system;

import cn.gson.crmdemo.common.JsonResult;
import cn.gson.crmdemo.model.Permission;
import cn.gson.crmdemo.model.dao.PermissionDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/system/permission")
@Slf4j
@Transactional(readOnly = true)
public class PermissionController {

    @Autowired
    private PermissionDao permissionDao;

    @RequestMapping
    public void  index(){

    }

    @RequestMapping({"/form","/load"})
    public String form(Long id, Model model){
        if(id!=null){
           Permission permission= permissionDao.findOne(id);
           model.addAttribute("permission",permission);
        }
        return "system/permission/form";
    }

    @RequestMapping("/list")
    @ResponseBody
    public List<Permission> list(){
        List<Permission> roots=permissionDao.findAllByParentIsNull();
        this.recursion(roots);
        return roots;
    }

    @RequestMapping("/getresouce")
    @ResponseBody
    public List<Permission> getResouce(){
        List<Permission> roots=permissionDao.findAllByParentIsNull();
        this.recursion(roots);
        return roots;
    }

    @PostMapping({"/save","/update"})
    @ResponseBody
    @Transactional
    public JsonResult save(@Valid  Permission permission, BindingResult bindingResult) {
        if (!bindingResult.hasErrors()) {
            permissionDao.save(permission);
            return JsonResult.success();
        } else {
            return JsonResult.error("校验不通过");
        }
    }

    @RequestMapping("/delete")
    @ResponseBody
    @Transactional
    public JsonResult delete(Long id){
      Permission permission= permissionDao.findOne(id);
      if(permission!=null){
        permissionDao.delete(permission);
          return JsonResult.success();
      }else{
          return JsonResult.error("数据不存在");
      }
    }

    private void recursion(List<Permission> roots){
        for (Permission root : roots) {
            List<Permission> children=permissionDao.findAllByParent(root);
            this.recursion(children);
            root.setChildren(children);
        }
    }
}
